import React, { useState, useEffect } from "react";
import styles from "./index.module.less";
import Nav from "@pages/nav";
import PortalContainer from "@components/portalContainer";
import QuestionShow from "@components/questionShow";
import MdRenderer from "@components/mdRenderer";
import MDEditor from "@uiw/react-md-editor";
import rehypeSanitize from "rehype-sanitize";
import Tag from "@components/tag";
import { useParams } from "react-router-dom";
import { request } from "@apis/request";
import profile from "@depjs/profile";
import moment from "moment";
import toast from "@utils/showToast";

const QuestionDetails = () => {
    const { questionId } = useParams();
    const [md, setMd] = useState("");
    const [title, setTitle] = useState("");
    const [cateTags, setCateTages] = useState([]);
    const [isResolved, setIsResolved] = useState(undefined);
    const [publishDate, setPublishDate] = useState(0);
    const [answers, setAnswers] = useState([]);
    const [focusNames, setFocusNames] = useState([]);
    const [rewardGmoney, setRewardGmoney] = useState(0);
    const [mdContent, setMdContent] = useState("");
    const [publishUser, setPublishUser] = useState("");
    const [loginUser, setLoginUser] = useState("");
    const [nick, setNick] = useState("");

    const getQuestions = async (questionId) => {
        const res = await request("/questions/receive", { type: questionId });
        console.log("res: ", res);
        if (res.code === "0000") {
            const {
                title,
                cateTags,
                isResolved,
                publishDate,
                answers,
                focusNames,
                rewardGmoney,
                mdContent,
                userName,
            } = res.data[0];
            setTitle(title);
            setCateTages(cateTags);
            setIsResolved(isResolved);
            setPublishDate(publishDate);
            setFocusNames(focusNames);
            setRewardGmoney(rewardGmoney);
            setMdContent(mdContent);
            setPublishUser(userName);
            // 拼接answers，被采纳的答案将被置顶
            let a = [].concat(answers);
            let a1 = a.filter((item) => item.isAccepted === true);
            let a2 = a.filter((item) => item.isAccepted === false);
            setAnswers([...a1, ...a2]);
        }
    };

    const submitAnswer = async () => {
        const res = await request(
            "/questions/submitAnswer",
            {
                answerMdContent: md,
                nick,
                questionId,
            },
            "post"
        );
        console.log("res: ", res);
        if (res.code === "0000") {
            toast.success("回答成功");
            setMd("");
            getQuestions(questionId);
        } else {
            toast.fail(res.msg);
        }
    };

    const handleAccept = async (questionId, answerId) => {
        const res = await request(
            "/questions/accept",
            { questionId, answerId },
            "post"
        );
        console.log("res: ", res);
        if (res.code === "0000") {
            toast.success(`采纳答案${answerId}成功！`);
            getQuestions(questionId);
        } else {
            toast.fail(res.msg);
        }
    };

    const handleFocus = async (questionId, e) => {
        if (e.target.value === "已关注") return;
        const res = await request("/questions/focus", { questionId }, "post");
        console.log("res: ", res);
        if (res.code === "0000") {
            toast.success("成功关注了该问题");
            getQuestions(questionId);
        } else {
            toast.fail(res.msg);
        }
    };

    useEffect(() => {
        getQuestions(questionId);
        profile.ready(() => {
            setLoginUser(profile.userName);
            setNick(profile.nick);
        });
    }, [questionId]);

    return (
        <div className={styles.question_details}>
            <Nav />
            <div className={styles.details_main}>
                {loginUser ? (
                    loginUser === publishUser ? (
                        <div className={styles.operation}>
                            <span className={styles.edit_question}>
                                重新编辑该问题
                            </span>
                        </div>
                    ) : undefined
                ) : undefined}
                <div className={styles.show_head}>
                    <QuestionShow
                        title={title}
                        cateTags={cateTags}
                        isResolved={isResolved}
                        publishDate={publishDate}
                        numbers={answers.length}
                        focusNames={focusNames}
                        rewardGmoney={rewardGmoney}
                        isShowTag={true}
                    />
                </div>
                <div className={styles.description}>
                    <MdRenderer source={mdContent} />
                    <div className={styles.focus_wrap}>
                        {loginUser ? (
                            loginUser === publishUser ? undefined : (
                                <input
                                    type="button"
                                    value={
                                        focusNames.includes(loginUser)
                                            ? "已关注"
                                            : "关注该问题"
                                    }
                                    className={styles.focus_answer}
                                    onClick={(e) => {
                                        handleFocus(questionId, e);
                                    }}
                                />
                            )
                        ) : undefined}
                    </div>
                </div>
                <div className={styles.editor_container}>
                    <MDEditor
                        height={180}
                        value={md}
                        onChange={setMd}
                        previewOptions={{
                            rehypePlugins: [[rehypeSanitize]],
                        }}
                        visibleDragbar={false}
                    />
                    <div className={styles.bottom}>
                        <p className={styles.full_tips}>
                            👆回答内容较多时，可点击编辑器右上角icon，进行全屏编辑哦~
                        </p>
                        <input
                            type="button"
                            value="提交回答"
                            className={styles.submit_answer}
                            onClick={submitAnswer}
                        />
                    </div>
                </div>
                <div className={styles.answers}>
                    <p className={styles.answers_head}>回答区</p>
                    <ul className={styles.answers_ul}>
                        {answers &&
                            answers.map((item, index) => {
                                return (
                                    <li key={item.answerId}>
                                        {item.isAccepted ? (
                                            <div className={styles.accept_tag}>
                                                <Tag
                                                    type="success"
                                                    tag="问友已采纳"
                                                />
                                            </div>
                                        ) : undefined}
                                        <MdRenderer
                                            source={item.answerMdContent}
                                        />
                                        <div className={styles.answer_info}>
                                            <p className={styles.answer_sort}>
                                                #{item.answerId}
                                            </p>
                                            <p className={styles.rig}>
                                                {loginUser ? (
                                                    loginUser ===
                                                    publishUser ? (
                                                        isResolved ? undefined : (
                                                            <input
                                                                type="button"
                                                                value="采纳"
                                                                className={
                                                                    styles.accept_it
                                                                }
                                                                onClick={() => {
                                                                    handleAccept(
                                                                        questionId,
                                                                        item.answerId
                                                                    );
                                                                }}
                                                            />
                                                        )
                                                    ) : undefined
                                                ) : undefined}
                                                <span className={styles.nick}>
                                                    {item.answerUserName}
                                                </span>
                                                <span
                                                    className={
                                                        styles.answer_date
                                                    }
                                                >
                                                    {moment(
                                                        item.answerDate
                                                    ).format(
                                                        "YYYY年MM月DD日 HH:mm:ss"
                                                    )}
                                                </span>
                                            </p>
                                        </div>
                                    </li>
                                );
                            })}
                    </ul>
                </div>
            </div>
            <PortalContainer />
        </div>
    );
};

export default QuestionDetails;
